from flask import Blueprint, jsonify, request

from src import db
from src.models.export_task import ExportTask
from src.tasks.export_tasks import export_data
from src.tasks.split_pdf_task import split_pdf_task

api_bp = Blueprint("api", __name__)


@api_bp.route("/export", methods=["POST"])
def create_export_task():
    """创建导出数据任务"""
    task_name = request.json.get("task_name")
    export_type = request.json.get("export_type", "csv")
    query_params = request.json.get("query_params", "{}")

    new_task = ExportTask(task_name=task_name, export_type=export_type, query_params=query_params)
    db.session.add(new_task)
    db.session.commit()

    # 异步执行导出任务
    export_data.apply_async(args=[new_task.task_id], task_id=new_task.task_id)

    return jsonify(
        {
            "task_id": new_task.task_id,
            "status": new_task.status.value,
        }
    ), 202


@api_bp.route("/export/<task_id>", methods=["GET"])
def get_export_task_status(task_id):
    """获取任务状态"""
    task = ExportTask.query.filter_by(task_id=task_id).first()
    if not task:
        return jsonify({"error": "任务不存在"}), 404
    return jsonify(task.to_dict())


@api_bp.route("/split/<file_url>", methods=["GET"])
def split_document(file_url):
    task_result = split_pdf_task.apply_async(args=[file_url])
    # 阻塞，同步等待获取任务结束返回的结果,可以设置最大等待时间
    # task_output = task_result.get(timeout=20)
    # print("task_output",task_output)

    # celery任务唯一ID
    celery_task_id = task_result.id
    return jsonify({"success": True, "task_id": celery_task_id}), 200
